<template>
    <div v-if="userInfo">
        <input type="file" class="file" ref="file" @change="uploadFile" />
        <el-avatar
            v-if="userInfo.avatar"
            :src="userInfo.avatar.replace(/public/,baseURL)"
            @click="clickToUpload"
        />
        <el-avatar
            v-else
            :src="src"
            @click="clickToUpload"
        />
    </div>
</template>

<script>
import {computed, onMounted, reactive,toRefs,ref} from 'vue'
import { useStore } from 'vuex'
import { ajax } from '@/api'

export default {
    setup(props){
        const store = useStore()
        const file = ref()
        const state = reactive({
            // src:'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            src:require('@/assets/images/Pikachu.jpg'),
            
        })
        onMounted(()=>{
            
        })
        const clickToUpload=()=>{
            file.value.click() // 触发 file/input 的点击事件 
        }
        const uploadFile = async ()=>{
            console.log("upload")
            const filedata = file.value.files[0]
            console.log(filedata)
            // 表单对象发送文件数据
            const data = new FormData()
            data.append("file",filedata)

            let res = await ajax.uploadfile(data);   // 上传图片
            let {code,result} = await ajax.changeuser({
                avatar:res.path  // 头像路径 
            })
            // 修改userInfo 
            if(code==200){
                   // 修改头像 
                store.commit("changeUserInfo",{...store.state.userInfo,avatar:res.path})
            }

        }
        const userInfo = computed(()=>store.state.userInfo)
        return {
            ...toRefs(state),
            userInfo,
            file,
            clickToUpload,
            uploadFile
        }
    }
}
</script>

<style scoped>
.file{
    display: none;
}
</style>